package com.rr.mymoney.dao.impl.hibernate;

import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.rr.mymoney.dao.MonthBudgetDao;
import com.rr.mymoney.model.MonthBudget;

@Repository
public class MonthBudgetDaoImpl extends AbstractDao implements MonthBudgetDao {
    public void saveOrUpdate(MonthBudget monthBudget) {
	getCurrentSession().saveOrUpdate(monthBudget);
	getCurrentSession().flush();
    }

    public MonthBudget get(Long id) {
	return (MonthBudget) getCurrentSession().get(MonthBudget.class, id);
    }

    public void delete(MonthBudget monthBudget) {
	getCurrentSession().delete(monthBudget);
    }

    @SuppressWarnings("unchecked")
    public List<MonthBudget> getByUserIds(List<Long> userIds) {
	if (!CollectionUtils.isEmpty(userIds)) {
	    return findByNamedParam("from MonthBudget where user.id in (:userIds)", new String[] { "userIds" }, new Object[] { userIds });
	} else {
	    return find("from MonthBudget where user.id is null");
	}
    }

    @SuppressWarnings("unchecked")
    public List<MonthBudget> getGenericBudget(List<Long> userIds) {
	if (!CollectionUtils.isEmpty(userIds)) {
	    return findByNamedParam("from MonthBudget where month is null and year is null and user.id in (:userIds)",
		    new String[] { "userIds" }, new Object[] { userIds });
	} else {
	    return find("from MonthBudget where month is null and year is null and user.id is null");
	}
    }

    @SuppressWarnings("unchecked")
    public List<MonthBudget> getGenericMonthlyBugdet(List<Long> userIds, int month) {
	if (!CollectionUtils.isEmpty(userIds)) {
	    return findByNamedParam("from MonthBudget where month = :month and year is null and user.id in (:userIds)", new String[] {
		    "month", "userIds" }, new Object[] { month, userIds });
	} else {
	    return find("from MonthBudget where month = ? and year is null and user.id is null", month);
	}
    }

    @SuppressWarnings("unchecked")
    public List<MonthBudget> getSpecificMonthlyBugdet(List<Long> userIds, int month, int year) {
	if (!CollectionUtils.isEmpty(userIds)) {
	    return findByNamedParam("from MonthBudget where month = :month and year = :year and user.id in (:userIds)", new String[] {
		    "month", "year", "userIds" }, new Object[] { month, year, userIds });
	} else {
	    return find("from MonthBudget where month = ? and year = ? and user.id is null", new Object[] { month, year });
	}
    }
}
